﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SMS_Agent.Model;
using SMS_Agent.BLL;
using SmsControl;

namespace SMS_Agent.View
{
    public partial class frmMain : Form
    {
        List<notify> currentList;
        notify currentObj;
        SMS_DB2Entities dbEntities;

        SmsControl.SmsControl control;


        public frmMain()
        {
            InitializeComponent();
            control = new SmsControl.SmsControl();
        }

        public static Model.SMS_DB2Entities getDbEntities()
        {
            //if (RootStaticVar.DbEntities == null)
            //{
            //    //RootStaticVar.DbEntities = new Model.Entities(RootStaticVar.EntityConnection);
            //    //RootStaticVar.DbEntities = new Model.AnimalCareEntities(1);
            //    RootStaticVar.DbEntities = new Model.SMS_DB2Entities();
            //}
            //return (Model.SMS_DB2Entities)RootStaticVar.DbEntities;

            return (new SMS_DB2Entities());
        }


        private void ReceiveSMS(List<SmsControl.SMS> smslist)
        {
            if (smslist == null) { return; }
            if (smslist.Count == 0) { return; }
            try
            {
                notify not;
                List<notify> listNotify = new List<notify>();
                string makhachhang;
                int group;
                string content;
                DateTime thoigian;
                foreach (SMS sms in smslist)
                {
                    makhachhang = sms.Content.Substring(0, 4);
                    group = int.Parse(sms.Content.Substring(4, 1));
                    content = sms.Content.Substring(5);
                    thoigian = sms.Date;
                    not = new notify();
                    not.isxuly = false;
                    not.makhachhang = makhachhang;
                    not.thongbao = content;
                    not.group_id = group;
                    not.thoigian = thoigian;
                    listNotify.Add(not);
                }

                foreach (notify n in listNotify)
                {
                    InsertObj(n);
                }
            }
            catch (Exception ex)
            {
            }

            LoadAllNotify();
            LoadDataToGridView(currentList);
            LoadObject(currentList[0]);
        }        
        
        private void LoadAllNotify()
        {
            dbEntities = getDbEntities();
            currentList = dbEntities.notify.OrderBy(x => x.isxuly).ThenByDescending(x => x.thoigian).ToList();
        }

        private void LoadObject(notify obj)
        {
            frmDetail frm = new frmDetail(obj);
            DialogResult res = frm.ShowDialog();

            if (res == System.Windows.Forms.DialogResult.Yes)
            {
                obj.isxuly = true;
                UpdateObj(obj);
            }
            LoadAllNotify();
            LoadDataToGridView(currentList);
        }

        private void InsertObj(notify obj)
        {
            try
            {
                if (dbEntities.Entry(obj) == null) { dbEntities.notify.Attach(obj); }
                dbEntities.Entry(obj).State = System.Data.EntityState.Added;
                //dbEntities.SaveChanges();
                dbEntities.SaveChanges();
            }
            catch (Exception ex)
            {
            }
        }

        private void UpdateObj(notify obj)
        {
            try
            {
                if (dbEntities.Entry(obj) == null) { dbEntities.notify.Attach(obj); }
                dbEntities.Entry(obj).State = System.Data.EntityState.Modified;
                //dbEntities.SaveChanges();
                dbEntities.SaveChanges();
            }
            catch (Exception ex)
            {
            }
        }

        delegate void LoadDataToGridViewCallback(List<notify> list);

        private void LoadDataToGridView(List<notify> list)
        {
            if (this.InvokeRequired)
            {
                LoadDataToGridViewCallback d = new LoadDataToGridViewCallback(LoadDataToGridView);
                this.Invoke(d, new object[] { list });
            }
            else
            {

                DataGridViewRow row;

                dgvData.Rows.Clear();

                try
                {
                    int numberOfItem = list.Count;

                    if (numberOfItem <= 0) { return; }

                    notify obj;
                    dgvData.Rows.Add(numberOfItem);

                    for (int i = 0; i < numberOfItem; i++)
                    {
                        row = dgvData.Rows[i];
                        obj = list[i];

                        row.Cells["colThoiGian"].Value = obj.thoigian.ToString("dd-MM-yyyy HH:mm:ss");
                        row.Cells["colKhachHang"].Value = obj.khachhang.tenkhachhang;
                        row.Cells["colDiaChi"].Value = obj.khachhang.diachi;
                        row.Cells["colSuCo"].Value = obj.thongbao;
                        row.Cells["colDaXuLy"].Value = obj.isxuly;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.ColumnIndex < dgvData.Columns.Count && e.RowIndex >= 0 && e.RowIndex < currentList.Count)
            {
                currentObj = currentList[e.RowIndex];
                LoadObject(currentObj);

                //pgChiTiet.Enabled = true;
                //tbTatCa.SelectedTab = pgChiTiet;
                //labNameForm.Text = "Thêm mới thông tin".ToUpper();
                //isNew = false;
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            frmLoadPort frm = new frmLoadPort();
            DialogResult res = frm.ShowDialog();

            if (res != System.Windows.Forms.DialogResult.OK)
            {
                Environment.Exit(0);
            }

            control.Initialize(frm.COMPort);

            LoadAllNotify();
            LoadDataToGridView(currentList);

            control.NewMessageReceived += ReceiveSMS;
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }


    }
}
